package com.ndood.gateway.app.exception;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import com.ndood.api.base.exception.ApiException;
import com.ndood.gateway.base.pojo.GatewayErrorVo;

import lombok.extern.slf4j.Slf4j;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
@Slf4j
public class ApiExceptionHandler {

	public static final Integer DEFAULT_ERROR_CODE = 11001;
	public static final String DEFAULT_MESSAGE = "未知系统错误";
	public static final String DEFAULT_ERROR_VIEW = "error";

	/**
	 * 判断是否是json请求
	 */
	public Boolean isJson(HttpServletRequest request) {
		boolean isJson = request.getHeader("content-type") != null
				&& request.getHeader("content-type").contains("json");
		return isJson;
	}

	/**
	 * 判断是否是ajax请求
	 */
	public static boolean isAjax(HttpServletRequest httpRequest) {
		boolean isAjax = httpRequest.getHeader("X-Requested-With") != null
				&& "XMLHttpRequest".equals(httpRequest.getHeader("X-Requested-With").toString());
		return isAjax;
	}

	/**
	 * 全局异常处理
	 */
	@ExceptionHandler(value = Exception.class)
	public Object errorHandler(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception {
		log.error(e.getMessage(),e);

		if (isAjax(request) || isJson(request)) {
			GatewayErrorVo error = new GatewayErrorVo();
			if (e instanceof ApiException) {
				ApiException se = (ApiException) e;
				error.setCode(se.getCode() == null ? DEFAULT_ERROR_CODE : se.getCode().getCode());
				error.setMsg(se.getMessage() == null ? DEFAULT_MESSAGE : se.getMessage());
				return error;
			}
			error.setCode(DEFAULT_ERROR_CODE);
			error.setMsg(e.getMessage() == null? DEFAULT_MESSAGE : e.getMessage());
			return error;

		}
		ModelAndView mv = new ModelAndView();
		mv.addObject("exception", e);
		mv.addObject("url", request.getRequestURL());
		mv.setViewName(DEFAULT_ERROR_VIEW);
		return mv;
	}
	
}